<template>
  <div class="assignment-history">
    <!-- 搜索和筛选栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="工单编号">
          <el-input
            v-model="searchForm.workOrderNo"
            placeholder="请输入工单编号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="分配类型">
          <el-select
            v-model="searchForm.assignmentType"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="初始分配" value="initial" />
            <el-option label="重新分配" value="reassign" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人">
          <el-select
            v-model="searchForm.operatorId"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="work_order_no" label="工单编号" min-width="150" />
      <el-table-column
        prop="work_order_title"
        label="工单标题"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column label="分配变更" width="250">
        <template #default="scope">
          <div class="assignment-change">
            <div class="from-to">
              <el-tag type="info" v-if="scope.row.from_assignee_name">
                {{ scope.row.from_assignee_name }}
              </el-tag>
              <span v-else>-</span>
              <span class="arrow">→</span>
              <el-tag type="success">{{ scope.row.to_assignee_name }}</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="assignment_type" label="分配类型" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.assignment_type === 'initial'" type="primary">初始分配</el-tag>
          <el-tag v-else type="warning">重新分配</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operator_name" label="操作人" width="120" />
      <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      <el-table-column prop="create_time" label="分配时间" width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 统计信息 -->
    <div class="stats">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">总分配次数</div>
          <div class="stat-value">{{ stats.total_assignments }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">重新分配次数</div>
          <div class="stat-value">{{ stats.reassignments }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">本月分配次数</div>
          <div class="stat-value">{{ stats.this_month }}</div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'

  // 类型定义
  interface User {
    id: number
    name: string
  }

  interface AssignmentRecord {
    id: number
    work_order_no: string
    work_order_title: string
    from_assignee_name?: string
    to_assignee_name: string
    assignment_type: 'initial' | 'reassign'
    operator_name: string
    remark: string
    create_time: number | string
  }

  // 搜索表单
  const searchForm = reactive({
    workOrderNo: '',
    assignmentType: '',
    operatorId: '',
  })

  // 表格数据
  const tableData = ref<AssignmentRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0,
  })

  // 统计数据
  const stats = reactive({
    total_assignments: 0,
    reassignments: 0,
    this_month: 0,
  })

  // 用户选项
  const userOptions = ref<User[]>([])

  // 初始化
  onMounted(() => {
    fetchData()
    fetchStats()
    fetchUserOptions()
  })

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      // TODO: 调用API获取分配历史
      // const response = await fetchAssignmentHistory({
      //   ...searchForm,
      //   page: pagination.page,
      //   limit: pagination.limit
      // })
      // tableData.value = response.list
      // pagination.total = response.total
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      // TODO: 调用API获取统计数据
      // const response = await fetchAssignmentStats()
      // Object.assign(stats, response)
    } catch (error) {
      console.error(error)
    }
  }

  // 获取用户选项
  const fetchUserOptions = async () => {
    try {
      // TODO: 调用API获取用户列表
      userOptions.value = []
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  // 重置
  const handleReset = () => {
    searchForm.workOrderNo = ''
    searchForm.assignmentType = ''
    searchForm.operatorId = ''
    handleSearch()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    pagination.limit = val
    fetchData()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchData()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }
</script>

<style lang="scss" scoped>
  .assignment-history {
    padding: 20px;

    .search-bar {
      background: #f5f5f5;
      padding: 20px;
      border-radius: 4px;
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      text-align: right;
    }

    .stats {
      display: flex;
      gap: 20px;
      margin-top: 20px;

      .stat-card {
        flex: 1;

        .stat-item {
          text-align: center;

          .stat-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #409eff;
          }
        }
      }
    }

    .assignment-change {
      .from-to {
        display: flex;
        align-items: center;
        gap: 10px;

        .arrow {
          font-size: 18px;
          color: #409eff;
        }
      }
    }
  }
</style>
